<template>
  <div id="wrap">
    <div id="city-search">
      <input v-model="keyword" class="input" type="text" placeholder="输入城市或拼音">
    </div>
    <div class="search" ref="wrapper" v-show="keyword">
      <ul>
        <li v-for="item of list" :key="item.id" @click="chooseCity(item.name)">{{item.name}}</li>
        <li v-show="shownodata" style="text-align: center;">没有找到匹配项</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
export default{
  name: 'citySearch',
  props: {
    abc: Object
  },
  data () {
    return {
      keyword: '',
      timer: null,
      list: []
    }
  },
  computed: {
    shownodata () {
      return !this.list.length
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.wrapper)
  },
  methods: {
    chooseCity (city) {
      this.$store.commit('cCity', city)
      this.$router.push('/')
    }
  },
  watch: {
    keyword (e) {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let key in this.abc) {
          this.abc[key].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '~stylee/stylus'
  #city-search
    background-color $bgColor
    padding: 4px 10px;
    padding-top: 0;
    .input
      box-sizing border-box
      width: 100%;
      height: 28px;
      border-radius 4px
      padding: 0 4px;
      border none
      text-align center
  .search
    z-index 2
    position absolute
    top: 72px;
    bottom: 0;right: 0;left: 0;
    overflow: hidden;
    background-color #eee
    ul
      padding: 5px 0;
      li
        color #212121
        font-size: 14px;
        padding: 5px;
        margin: 1px;
        line-height: 22px;
        background-color #fff
</style>
